/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.acme.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
 *
 * @author General
 */
public class YQLclient {
   
    /**
     *  This method takes a Yahoo Query (YQL) and a java class to marshall the 
     *  xml result to, does the HTTP GET call to yahoo,  
     *  and uses JAX-B to create a response object. 
     */
    public Object doCall (String query, Class contextClass) throws Exception {
        //JAXBContext jc = JAXBContext.newInstance(Stock.class);
        JAXBContext jc = JAXBContext.newInstance(contextClass);
        
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        //URL url = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22MSFT%22)%20and%20startDate%3D%222011-2-12%22%20and%20endDate%3D%222011-2-15%22%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env");
        URL url = new URL(query);
        InputStream xmlStream = url.openStream();
        //Stock stock = (Stock) unmarshaller.unmarshal(xmlStream);
        Object result = unmarshaller.unmarshal(xmlStream);
        
        /* TRAZA PARA LA CONSOLA
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(result, System.out);
        */
        
        return result;
    }
    
    /**
     *  This method is a simple test to see the results of a Yahoo Query (YQL)
     *  in the console. 
     */
    public void doQueryTest(){
        try {
            URL yahoo = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3DYHOO%2CGOOG%2CAAPL%26f%3Dsl1d1t1c1ohgv%26e%3D.csv'%20and%20columns%3D'symbol%2Cprice%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2'&diagnostics=true");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine;
            
            while ((inputLine = in.readLine()) != null) 
                System.out.println(inputLine);
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(YQLclient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(YQLclient.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
}
